<?php
/**
 * Created by PhpStorm.
 * Author: wenwenbin
 * Date: 2017/12/22
 * Time: 11:21
 */
namespace App\Http\Admin\Personnel\Controllers;

use App\Http\Admin\AppManage\Models\UserRole;
use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Personnel\Models\AddressList;
use App\Api\Foundation\Upload\Models\ImageUpload;
use Framework\Services\Excel\LaravelExcel\LaravelExcelService;

class AddressListController extends Controller
{
    /**
     * 进入员工列表页面或获取员工列表数据
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Database\Eloquent\Collection|\Illuminate\Http\JsonResponse|\Illuminate\View\View|static[]
     */
    public function companyAddressList()
    {
        $company_id = session('current_operation_company_id');
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        try {
            if (request()->isMethod('post')) {
                $employee = new AddressList();
                return $employeeList = $employee->getEmployeeList($company_id);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('address-list');
    }

    public function personnelFileInfo()
    {
        $company_id = session('current_operation_company_id');
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $params = request(['employee_id']);
        $employee = new AddressList();
        try {
            $employeeInfo = $employee->getEmployeeInfo($params['employee_id']);
            $departmentList = $employee->getDepartmentList($company_id);
            $employeeNumberList = $employee->getEmployeeNumberList($company_id, $params['employee_id']);
            $userList = new UserRole();
            $roleList = $userList->roleListByCompanyId($company_id);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('personnel-file-info',
            [
                'employeeInfo'       => $employeeInfo,
                'departmentList'     => $departmentList,
                'employeeNumberList' => $employeeNumberList,
                'roleList'           => $roleList
            ]);
    }

    public function companyResumeInfo()
    {
        $params = request(['oa_contacts_id']);
        $employee = new AddressList();
        $result = $employee->getCompanyResumeInfo($params['oa_contacts_id']);
        return $this->view('company-resume-info', [
            'resumeInfo' => $result['resumeInfo'], 'workHistoryList' => $result['workHistoryList']
        ]);
    }

    /**
     * 添加员工
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function addressListMemberAdd()
    {
        $company_id = session('current_operation_company_id');
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $params = request()->only('oa_department_id', 'position', 'name', 'sex', 'role_id', 'ethnicity', 'birthplace', 'education',
            'birthdate', 'credential_type', 'credential_number', 'mobile', 'email', 'address', 'marital_status',
            'household_registratio_type', 'personnel_sources', 'health_certificate_term', 'profile_photo_url',
            'note', 'type', 'start_time', 'employee_number', 'accumulation_fund', 'accumulation_fund_base',
            'accumulation_fund_adjust_time', 'social_security_base', 'insured_adjust_time');
        $employee = new AddressList();
        try {
            if (request()->isMethod('post')) {
                $result = $employee->saveAddressListMember(null, $company_id, $params['oa_department_id'],
                    $params['position'], $params['name'], $params['sex'], $params['role_id'], $params['ethnicity'], $params['birthplace'],
                    $params['education'], $params['birthdate'], $params['credential_type'], $params['credential_number'],
                    $params['mobile'], $params['email'], $params['address'], $params['marital_status'],
                    $params['household_registratio_type'], $params['personnel_sources'], $params['health_certificate_term'],
                    $params['profile_photo_url'], $params['note'], $params['type'], $params['start_time'],
                    $params['employee_number'], $params['accumulation_fund'], $params['accumulation_fund_base'],
                    $params['accumulation_fund_adjust_time'], $params['social_security_base'], $params['insured_adjust_time']);
                return $result ? $this->jsonReturn(true) : $this->jsonReturn(false);
            }
            $departmentList = $employee->getDepartmentList($company_id);
            $employeeNumberList = $employee->getEmployeeNumberList($company_id);
            $userList = new UserRole();
            $roleList = $userList->roleListByCompanyId($company_id);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('address-list-member-add',
            [
                'departmentList'     => $departmentList,
                'employeeNumberList' => $employeeNumberList,
                'roleList'           => $roleList
            ]);
    }

    /**
     * 编辑员工
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function addressListMemberEdit()
    {
        $company_id = session('current_operation_company_id');
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $params = request()->only('oa_department_id', 'position', 'name', 'sex', 'role_id', 'ethnicity', 'birthplace', 'education',
            'birthdate', 'credential_type', 'credential_number', 'mobile', 'email', 'address', 'marital_status',
            'household_registratio_type', 'personnel_sources', 'health_certificate_term', 'profile_photo_url',
            'note', 'type', 'start_time', 'employee_number', 'accumulation_fund', 'accumulation_fund_base',
            'accumulation_fund_adjust_time', 'social_security_base', 'insured_adjust_time', 'employee_id');
        $employee = new AddressList();
        try {
            if (request()->isMethod('post')) {
                $result = $employee->saveAddressListMember($params['employee_id'], $company_id, $params['oa_department_id'],
                    $params['position'], $params['name'], $params['sex'], $params['role_id'], $params['ethnicity'], $params['birthplace'],
                    $params['education'], $params['birthdate'], $params['credential_type'], $params['credential_number'],
                    $params['mobile'], $params['email'], $params['address'], $params['marital_status'],
                    $params['household_registratio_type'], $params['personnel_sources'], $params['health_certificate_term'],
                    $params['profile_photo_url'], $params['note'], null, $params['start_time'], $params['employee_number'],
                    $params['accumulation_fund'], $params['accumulation_fund_base'], $params['accumulation_fund_adjust_time'],
                    $params['social_security_base'], $params['insured_adjust_time']);
                return $result ? $this->jsonReturn(true) : $this->jsonReturn(false);
            }
            $employeeInfo = $employee->getEmployeeInfo($params['employee_id']);
            $departmentList = $employee->getDepartmentList($company_id);
            $employeeNumberList = $employee->getEmployeeNumberList($company_id, $params['employee_id']);
            $userList = new UserRole();
            $roleList = $userList->roleListByCompanyId($company_id);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('address-list-member-edit',
            [
                'employeeInfo'       => $employeeInfo,
                'departmentList'     => $departmentList,
                'employeeNumberList' => $employeeNumberList,
                'roleList'           => $roleList
            ]);
    }

    /**
     * 员工离职
     * @author wenwenbin
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressListMemberDel()
    {
        $params = request()->all();
        if (request()->isMethod('post')) {
            $company_id = session('current_operation_company_id');
            if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
            $employee = new AddressList();
            try {
                $result = $employee->delAddressListMember($params['id'], $company_id,
                    $params['status'], $params['evaluate']);
            } catch (\DebugError $e) {
                return $this->ajaxFail($e->getMessage());
            }
            return $result ? $this->jsonReturn(true) : $this->jsonReturn(false);
        }
        return $this->view('address-list-member-del', ['id' => $params['id']]);
    }

    /**
     * 通讯录头像上传
     * @author wenwenbin
     * @return array
     */
    public function profilePhotoUpload()
    {
        $img = request()->file('file');
        $imageUpload = new ImageUpload();
        $fileInfo = $imageUpload->upload($img, 'address-list-profile-photo', null, true);
        \DebugBar::disable();
        return [
            'statusCode' => 200,
            'filename'   => $fileInfo['path']
        ];
    }

    public function addressListMemberImport()
    {
        try {
            if (request()->isMethod('post')) {
                if (request()->hasFile('employee') && request()->file('employee')->isValid()) {
                    $employee = new AddressList();
                    $electricityBill = request()->file('employee');
                    $extension = $electricityBill->getClientOriginalExtension();
                    $storage_path = storage_path('/exports');//上传文件保存的路径
                    if (!file_exists($storage_path)) {//如果$storage_path（文件保存的目录）不存在
                        mkdir($storage_path, 0777, true);//创建一个目录
                    }
                    $filename = md5(ceil(microtime(true) * 1000)) . '.' . $extension; //确保文件不重名
                    if ($electricityBill->move($storage_path, $filename) == false) return xThrow(ERR_HTTP_FILE_UPLOAD);
                    $excel = new LaravelExcelService();
                    $data = $excel->import($filename)->getSheet(0)->toArray();
                    global $insertData, $error, $err_count, $success_count;
                    $error = $employee->importEmployee($data);
                    if ($error) {
                        request()->session()->put('error', $error);//将要导出的内容存入session 键值为error
                        $message = '本次共导入' . ($success_count + $err_count) . '条数据,其中失败' . $err_count . '条,以下为未插入数据序号<br>' . implode(",", $error);
                        return xThrow(ERR_ADMIN_EXCEL_ERROR, $message);
                    }
                    return $this->ajaxSuccess();
                } else return xThrow(ERR_HTTP_FILE_UPLOAD);
            }
            return $this->view('address-list-member-import');
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
    }

    public function addressListTemplateDownload()
    {
        return response()->download(storage_path("template/employee/employee.xls"), "员工模板.xls");
    }

    /**
     * 获取公共模版通讯录员工数据
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Database\Eloquent\Collection|\Illuminate\Http\JsonResponse|\Illuminate\View\View|static[]
     */
    public function addressListEmployee()
    {

        //易管通项目，company_id获取方式不同
//            $companyId = session('current_operation_company_id');
        $adminUser = request()->user('admin')->toArray();
        $company_id = $adminUser['company_id'];
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        try {
            if (request()->isMethod('post')) {
                $employee = new AddressList();
                return $employeeList = $employee->getAddressListEmployeeList($company_id);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('address-list');
    }

    /**
     * 获取公共模版通讯录部门数据
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\Support\Collection|\Illuminate\View\View
     */
    public function addressListDepartment()
    {
        $company_id = session('current_operation_company_id');
        if (!$company_id) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        try {
            if (request()->isMethod('post')) {
                $employee = new AddressList();
                return $employeeList = $employee->getAddressListDepartmentList($company_id);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->view('address-list');
    }
}